package com.topscomm.mpm;

import javax.annotation.Resource;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.topscomm.app.pojo.AppPageEntity;
import com.topscomm.basic.BasicController;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.pojo.CboApprovalNodeInsEntity;
import com.topscomm.cbo.service.ICboApprovalNodeInsService;
import com.topscomm.cbo.service.ICboAttachmentService;
import com.topscomm.cbo.service.impl.CboAttachmentService;
import com.topscomm.mis.MisController;
import com.topscomm.mis.pojo.MisDeptArchEntity;
import com.topscomm.mpm.pojo.MpmProjectEntity;
import com.topscomm.mpm.pojo.MpmProjectSaleEntity;
import com.topscomm.mpm.pojo.MpmProjectWinBidInfoEntity;
import com.topscomm.mpm.service.impl.*;
import com.topscomm.pub.util.*;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.TapService;
import com.topscomm.tap.common.FlowDatacodeCache;
import com.topscomm.tap.common.TapSystemConst;
import lombok.SneakyThrows;
import org.omg.CORBA.Any;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

public class MpmController<T extends MpmEntity, TService extends IMpmService<T, ?>>
        extends MisController<T, TService> implements IMpmController<T, TService> {
    @Resource(name = "flowDatacodeCache")
    protected FlowDatacodeCache flowDatacodeCache;

    @Autowired
    protected ICboApprovalNodeInsService cboApprovalNodeInsService;
    @Autowired
    private MpmProjectService mpmProjectService;
    @Autowired
    private MpmProjectBidScoreService mpmProjectBidScoreService;
    @Autowired
    private MpmProjectWinBidInfoService mpmProjectWinBidInfoService;
    @Autowired
    private MpmProjectSaleService mpmProjectSaleService;
    @Autowired
    private MpmProjectProductInfoService mpmProjectProductInfoService;


    /**
     * @author: wudaliang
     * @date: 2021-08-05
     * @param: paraMap
     * @description: 判断该单据的最新阶段是否为当前用户审批
     * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @modify:
     */
    @GetMapping("/checkIsApproval")
    public ResponseResult<Object> checkIsApproval(@RequestParam(required = false) Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("isapprover", false);
        // 待审批的节点信息
        sql.appendSingle(" SOURCEID = '{0}' AND SOURCETYPE = '{1}' AND STATE = '1' " +
                        "AND APPROVALUSERID = {2} ", paraMap.get("sourceid"), paraMap.get("sourcetype"),
                this.getUserBean().getUser().getId());
        List<CboApprovalNodeInsEntity> cboApprovalNodeInsEntities = cboApprovalNodeInsService
                .queryByWhere(sql.toString());
        if (cboApprovalNodeInsEntities.size() > 0) {
            resultMap.put("isapprover", true);
            resultMap.put("nodeinsid", cboApprovalNodeInsEntities.get(0).getId());
        }
        return ResponseResult.ok(resultMap);
    }
    /**
     * @author: houyuhang
     * @date: 2021-05-10
     * @param: paraMap(code: 项目的projectcode; id: 项目id; deviceType: 设备类型)
     * @description: 加载项目详情各个tab数据
     * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @modify:
     */
    @GetMapping(value = "/loadMobileTotalPageInfo")
    public ResponseResult<Object> loadMobileTotalPageInfo(@RequestParam(required = false) Map<String, Object> paraMap) throws Exception {
        paraMap = BaseUtil.decodeSecureMap(paraMap);
        // 挂网时间
        String bidbegindate = "";
        // 开标时间
        String bidenddate = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 如果projectcode的值为null,则为消息跳转，需要根据id转到项目具体的projectcode
        if (ObjectUtil.isEmpty(paraMap.get("code"))) {
            MpmProjectEntity mpmProjectEntity = mpmProjectService.queryById(ConvertUtil.convertToString(paraMap.get("id")));
            if (ObjectUtil.isEmpty(mpmProjectEntity)) {
                return ResponseResult.error("获取信息失败,项目不存在");
            }
            paraMap.put("code", mpmProjectEntity.getProjectcode());
        }
        // 先获取所有的业务单据
        List<Map<String, Object>> pageList = datacodeCache.getCodeListMap("MobileTotalPage", "", "sortcode");
        if (pageList == null || pageList.size() == 0) {
            return ResponseResult.error("获取信息失败");
        }
        Map<String, Object> dataMap = new HashMap<>();
        List<Map> tabs = new ArrayList<>();
        for (Map pageMap : pageList) {
            Map<String, String> tab = new HashMap<>();
            tab.put("title", pageMap.get("name").toString());
            tab.put("key", pageMap.get("code").toString());
            String pageCode = pageMap.get("code").toString();
            Map<String, Object> myDadaMap = new HashMap<>();
            //查询页面配置的sql语句
            StringBufferProxy sqlForAppPage = new StringBufferProxy();
            StringBufferProxy sqlForAppPageTab = new StringBufferProxy();
            sqlForAppPage.appendSingle("code='{0}' and enabled=1", pageCode);
            //获取页面信息
            AppPageEntity page = appPageService.queryObjectByWhere(sqlForAppPage.toString());
            //获取tab信息
            sqlForAppPageTab.appendSingle("pageid='{0}' and enabled=1", page.getId());
            List<Map<String, Object>> appPageTabList = appPageTabService.queryMapByWhere(sqlForAppPageTab.toString());
            //获取主Tab(list中只有一个mainTab)
            List<Map<String, Object>> listMain = appPageTabList.stream().filter(b -> "mainList".equals(ConvertUtil.convertToString(b.get("code")))).collect(Collectors.toList());
            MpmController mainAction = null;
            if(MpmSystemConst.ProjectScoreCode.second.equals(ConvertUtil.convertToString(pageMap.get("code")))){
                mainAction = (MpmController) SpringUtil.getBean(toLowerCaseFirstOne(MpmSystemConst.ProjectScoreCode.first)+"Controller");
            } else {
                mainAction = (MpmController) SpringUtil.getBean(toLowerCaseFirstOne(ConvertUtil.convertToString(pageMap.get("code"))) + "Controller");
            }
            Map<String, Object> mainTab = listMain.get(0);
            Map<String, Object> mainListData = null;
            if (pageCode.equals("MpmProject")) {
                mainListData = mainAction.service.queryMapById(paraMap.get("id").toString());
                StringBufferProxy mpmInfoSql = new StringBufferProxy();
                mpmInfoSql.appendSingle("");
                MpmProjectSaleEntity projectSaleEntity = mpmProjectSaleService.queryById(paraMap.get("id").toString());
                if(projectSaleEntity.getBidbegindate()!=null){
                    bidbegindate = sdf.format(ConvertUtil.convertToDate(projectSaleEntity.getBidbegindate()));
                }
                if(projectSaleEntity.getBidenddate()!=null){
                    bidenddate = sdf.format(ConvertUtil.convertToDate(projectSaleEntity.getBidenddate()));
                }
            } else if (pageCode.equals("MpmProjectAppointment") || pageCode.equals("MpmProjectPlan") || pageCode.equals("MpmProjectReview")) {
                if (paraMap.containsKey("code") && paraMap.get("code").toString().length() > 0) {
                    List<Map<String, Object>> mainListDatas = mainAction.service.queryMapByWhere(" projectcode = '" + paraMap.get("code").toString() + "' order by id desc");
                    if (mainListDatas != null && mainListDatas.size() > 0) {
                        mainListData = mainListDatas.get(0);
                    }
                }
            } else {
                if (paraMap.containsKey("code") && paraMap.get("code").toString().length() > 0) {
                    StringBufferProxy sql = new StringBufferProxy();
                    sql.appendSingle(" projectcode = '{0}' ", ConvertUtil.convertToString(paraMap.get("code")));
                    if (pageCode.equals("MpmProjectTask")) {
                        // 如果为任务，修改排序
                        sql.appendSingle(" order by planenddate asc, planstartdate asc, id asc");
                    } else if (pageCode.equals(MpmSystemConst.ProjectScoreCode.first)) {
                        // 如果为评标细则，查询发布的第一次自评记录
                        sql.appendSingle(" and times = '{0}' and state = 9 order by type asc,id asc", MpmSystemConst.BidScoreTimes.firstTime);
                    }  else if (pageCode.equals(MpmSystemConst.ProjectScoreCode.second)) {
                        // 如果为评标细则，查询发布的第二次自评记录
                        sql.appendSingle(" and times = '{0}' and state = 9 and TYPE != '3' order by type asc,id asc", MpmSystemConst.BidScoreTimes.secondTime);
                    }else {
                        sql.appendSingle(" order by id desc");
                    }
                    List<Map<String, Object>> mainListDatas = mainAction.service.queryMapByWhere(sql.toString());
                    //添加附件信息
                    if(MpmSystemConst.ProjectScoreCode.first.equals(pageMap.get("code")) || MpmSystemConst.ProjectScoreCode.second.equals(pageMap.get("code"))) {
                        ICboAttachmentService cboAttachmentService = (CboAttachmentService) SpringUtil.getBean("cboAttachmentService");
                        sql.clear();
                        sql.appendSingle("sourceid = (select id from mpmproject where projectcode = '{0}') and sourcetype in ('MpmProjectBidScoreFirst')",
                                ConvertUtil.convertToString(paraMap.get("code")));
                        List<Map<String, Object>> attachList = new ArrayList<>();
                        List<String> fieldList = new ArrayList<>();
                        fieldList.add("filetype");
                        fieldList.add("filesize");
                        fieldList.add("displayname");
                        fieldList.add("sourcetype");
                        fieldList.add("id");
                        attachList = cboAttachmentService.queryMapFieldsByWhere(sql.toString(), fieldList);
                        myDadaMap.put("attachmentList", attachList);
                        sql.clear();
                        sql.appendSingle("sourceid = (select id from mpmproject where projectcode = '{0}') and sourcetype in ('MpmProjectBidScoreSecond')",
                                ConvertUtil.convertToString(paraMap.get("code")));
                        attachList = cboAttachmentService.queryMapFieldsByWhere(sql.toString(), fieldList);
                        myDadaMap.put("secondattachmentList", attachList);
                    }
                    // 查询除mainList外，其他tab页数据
                    if (mainListDatas != null && mainListDatas.size() > 0) {
                        myDadaMap.put("mainList", mainListDatas);
                        //查询其他tab数据
                        bindTabData(appPageTabList, myDadaMap, mainListDatas.get(0));
                        appPageService.getPageInfo(pageCode, myDadaMap);
                        tabs.add(tab);
                        dataMap.put(pageMap.get("code").toString(), myDadaMap);
                    }
                    // 如果第一次自评为空，查询第二次自评记录
//                    if (CollectionUtil.isEmpty(mainListDatas) && pageCode.equals("MpmProjectBidScore")) {
//                        bindTabDataForBidScore(appPageTabList, myDadaMap, ConvertUtil.convertToString(paraMap.get("code")));
//                        // 如果存在第二次自评，展示第二次自评
//                        if (!ObjectUtil.isEmpty(myDadaMap.get("secondList"))) {
//                            appPageService.getPageInfo(pageCode, myDadaMap);
//                            tabs.add(tab);
//                            dataMap.put(pageMap.get("code").toString(), myDadaMap);
//                        }
//                    }
                }
            }
            if (mainListData != null) {
                mainListData =  mainListExtraData(paraMap, mainListData,pageCode);
//                bindAttachment(paraMap,mainListData,pageCode);
                //将取出的详细数据放入
                List<Map<String, Object>> mainList = new ArrayList<>();
                mainList.add(mainListData);
                //塞入主表数据数据（数据的key约定为“表名+‘List’”）
                myDadaMap.put("mainList", mainList);
                //查询其他tab数据
                bindTabData(appPageTabList, myDadaMap, mainListData);
                appPageService.getPageInfo(pageCode, myDadaMap);
                tabs.add(tab);
                dataMap.put(pageMap.get("code").toString(), myDadaMap);
            }
        }
        dataMap.put("tabs", tabs);
        // 手机显示哪个tab
        long newDate = sdf.parse(sdf.format(new Date())).getTime();
        long bidbegindateins = 0;
        if(!bidbegindate.isEmpty()){
            bidbegindateins = sdf.parse(bidbegindate).getTime();
        }
        long bidenddateins = 0;
        if(!bidenddate.isEmpty()){
            bidenddateins = sdf.parse(bidenddate).getTime();
        }
//        Date date1 = format.parse(bidenddate);
//        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        System.out.println();
        // 如果有督办
        String showTab = "MpmProject";
        if(tabs.stream().filter( e -> ("MpmProjectSupervise".equals(ConvertUtil.convertToString(e.get("key"))))).collect(Collectors.toList()).size()>0){
            showTab = "MpmProjectSupervise";
        } else if (tabs.stream().filter( e -> ("MpmProjectSecondBidScore".equals(ConvertUtil.convertToString(e.get("key"))))).collect(Collectors.toList()).size()>0
                && bidenddateins >= newDate && bidenddateins > 0) {
            showTab = "MpmProjectSecondBidScore";
        } else if (tabs.stream().filter( e -> ("MpmProjectBidScore".equals(ConvertUtil.convertToString(e.get("key"))))).collect(Collectors.toList()).size()>0
                && bidbegindateins >= newDate && bidbegindateins > 0) {
            showTab = "MpmProjectBidScore";
        } else if (tabs.stream().filter( e -> ("MpmProjectPlan".equals(ConvertUtil.convertToString(e.get("key"))))).collect(Collectors.toList()).size()>0) {
            showTab = "MpmProjectPlan";
        }
        dataMap.put("showTab",showTab);
        return ResponseResult.ok(dataMap);
    }
    public void  bindAttachment(Map<String, Object> paraMap, Map<String, Object> mainListData, String pageCode){
        ICboAttachmentService cboAttachmentService = (CboAttachmentService) SpringUtil.getBean("cboAttachmentService");
        List<String> fieldList = new ArrayList<>();
        fieldList.add("filetype");
        fieldList.add("filesize");
        fieldList.add("displayname");
        fieldList.add("sourcetype");
        fieldList.add("id");
        List<Map<String, Object>> attachList = new ArrayList<>();
        // 如果是项目合同信息则只需要根据sourceid查询即可（合同流程中有多个附件）
        if (this.service.getDao().getTableName().equals("PmContract")) {
            StringBufferProxy whereSqlForAttachList = new StringBufferProxy();
            whereSqlForAttachList.appendSingle("sourceid = '{0}' and sourcetype in ('PmContract','PmSignContract') ", ConvertUtil.convertToString(mainListData.get("id")));
            attachList = cboAttachmentService.queryMapFieldsByWhere(whereSqlForAttachList.toString(), fieldList);
        } else {
            attachList = cboAttachmentService.queryMapFieldsByWhere("sourceid=" + ConvertUtil.convertToString(mainListData.get("id")) + " and sourcetype='" + pageCode + "'", fieldList);

        }
        mainListData.put("attachmentList", attachList);
    }
    // 其他页签绑定数据
    public void bindTabData(List<Map<String, Object>> appPageTabList, Map<String, Object> myDadaMap, Map<String, Object> mainListData) throws Exception {
        for (Map<String, Object> tabItem : appPageTabList) {
            if (!"mainList".equals(ConvertUtil.convertToString(tabItem.get("code")))) {
                // 子表action
                MpmController basicSubAction = (MpmController) SpringUtil.getBean(ConvertUtil.convertToString(tabItem.get("extendfield1")));
                //查询子表数据的sql语句
                StringBufferProxy sqlForSub = new StringBufferProxy();
                //主tab字段名称
                String mainTabFieldStr = ConvertUtil.convertToString(tabItem.get("extendfield2"));
                //此tab字段名称
                String subTabFieldStr = ConvertUtil.convertToString(tabItem.get("extendfield3"));
                // app模板页面id
                String tabTemplateId = ConvertUtil.convertToString(tabItem.get("extendfield4"));
                //拼装此tab需要的sql
                sqlForSub.appendSingle(" {0} = '{1}' ", subTabFieldStr, ConvertUtil.convertToString(mainListData.get(mainTabFieldStr)));
                // 如果是里程碑及任务，拼接上排序条件
                if ("MpmProjectMilepost".equals(ConvertUtil.convertToString(tabItem.get("relationdata")))) {
                    sqlForSub.appendSingle(" order by sortcode asc, planfinishtime asc, id asc ");
                }
                // 如果是评分细则，拼接sql
                if ("secondList".equals(ConvertUtil.convertToString(tabItem.get("relationdata")))) {
                    sqlForSub.appendSingle(" and times = '{0}' and state = 9 order by type asc,id asc ", MpmSystemConst.BidScoreTimes.secondTime);
                }
                // 复盘-评分细则内容，修改sql
                if("MpmProjectBidScoreReview".equals(ConvertUtil.convertToString(tabItem.get("relationdata")))) {
                    sqlForSub.appendSingle(" and times = '{0}' and type in ({1}) order by type asc, id asc ", MpmSystemConst.BidScoreTimes.thirdTime, MpmSystemConst.BidScoreType.firstType + "," + MpmSystemConst.BidScoreType.secondType);
                }
                if ("MpmProjectBidScoreOfferReview".equals(ConvertUtil.convertToString(tabItem.get("relationdata")))) {
                    sqlForSub.appendSingle(" and times = '{0}' and type = '{1}' and targetscore is not null order by type asc, id asc ", MpmSystemConst.BidScoreTimes.thirdTime, MpmSystemConst.BidScoreType.thirdType);
                }
                //查询子表数据
                List<Map<String, Object>> subList = basicSubAction.service.queryMapByWhere(sqlForSub.toString());
                // 复盘-评分细则内容，转换clob字段
                if ("MpmProjectBidScoreReview".equals(ConvertUtil.convertToString(tabItem.get("relationdata")))) {
                    mpmProjectBidScoreService.convertClobToStringBidScore(subList);
                }
                // 复盘-中标信息内容，不显示老中标金额
                if ("MpmProjectWinbidinfo".equals(ConvertUtil.convertToString(tabItem.get("relationdata")))) {
                    mpmProjectWinBidInfoService.changeBidMoney(subList);
                }
                //将取出的详细数据放入
                myDadaMap.put(ConvertUtil.convertToString(tabItem.get("relationdata")), subList);
            }
        }
    }

    //首字母转小写
    public static String toLowerCaseFirstOne(String s) {
        if (Character.isLowerCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
    }

    /**
     * 添加额外的数据项
     *
     * @param paraMap
     * @param mainListData
     */
    public Map<String,Object> mainListExtraData(Map<String, Object> paraMap, Map<String, Object> mainListData, String pageCode) {
        if (pageCode.equals("MpmProject")) {
            Map<String, Object> dataMapsale = mpmProjectSaleService.queryMapById(paraMap.get("id").toString());
            if (!dataMapsale.isEmpty()) {
                String participatemoneyStr = ConvertUtil.convertToString(dataMapsale.get("participatemoney"));
                dataMapsale.put("participatemoney", formatMonty(participatemoneyStr, 9, 2));
                mainListData.putAll(dataMapsale);
            }
            //涉及产品范围
            List<Map<String, Object>> productList = mpmProjectProductInfoService.queryMapByWhere(" projectid = '" + ConvertUtil.convertToString(paraMap.get("id")) + "'");
            StringBufferProxy productInfoPorxy = new StringBufferProxy();
            if (!CollectionUtil.isEmpty(productList)) {
                for (Map map : productList) {
                    //产品名称，线索显示产品大类，机会点显示产品中类
                    String cboItemCode = MpmSystemConst.MpmProjectSource.lead.equals(ConvertUtil.convertToString(dataMapsale.get("projectsource"))) ? "ProductCatalog1" : "ProductCatalog2";
                    String product = datacodeCache.getValueDynamic(cboItemCode, ConvertUtil.convertToString(map.get("productcode")),"code", "name");
                    //产品金额
                    String money = ConvertUtil.convertToString(map.get("fund"));
                    if (money.length() > 0) {
                        //金额格式化 追加万元
                        money = formatMonty(money, 9, 2);
                    }
                    productInfoPorxy.appendLineSingle(product + "-" + money);
                }
            }
            mainListData.put("productrange", productInfoPorxy.toString());
        }
        return  mainListData;
    }
    /**
     * @author: wudaliang
     * @date: 2021-06-22
     * @param: value
     * @param: maxDigit
     * @param: minDigit
     * @description:格式化金额
     * @return: java.lang.String
     * @modify:
     */
    protected String formatMonty(String value, int maxDigit, int minDigit) {
        if (value != null && !value.equals("")) {
            try {
                BigDecimal bigDecimal = new BigDecimal(value);
                NumberFormat currency = NumberFormat.getNumberInstance();
                currency.setMaximumFractionDigits(maxDigit);
                currency.setMinimumFractionDigits(minDigit);
                String s = currency.format(bigDecimal.doubleValue());
                value = s + "万元";
                return value;
            } catch (Exception var7) {
                return value;
            }
        } else {
            return "";
        }
    }
    /**
     * @author: houyuhang
     * @date: 2022-05-26
     * @description:评标细则第一次为空,获取第二次数据
     * @return: void
     * @modify:
     */
    public void bindTabDataForBidScore(List<Map<String, Object>> appPageTabList, Map<String, Object> myDadaMap, String projectcode) {
        for (Map<String, Object> tabItem : appPageTabList) {
            if (!"mainList".equals(ConvertUtil.convertToString(tabItem.get("code")))) {
                // 子表action
                MpmController basicSubAction = (MpmController) SpringUtil.getBean(ConvertUtil.convertToString(tabItem.get("extendfield1")));
                //查询子表数据的sql语句
                StringBufferProxy sqlForSub = new StringBufferProxy();
                sqlForSub.appendSingle(" projectcode = '{0}' and times = '{1}' and state = 9 order by type asc,id asc ", projectcode, MpmSystemConst.BidScoreTimes.secondTime);
                //查询子表数据
                List<Map<String, Object>> subList = basicSubAction.service.queryMapByWhere(sqlForSub.toString());
                //如果子表没有数据，直接return
                if (CollectionUtil.isEmpty(subList)) {
                    return;
                }
                //将取出的详细数据放入
                myDadaMap.put(ConvertUtil.convertToString(tabItem.get("relationdata")), subList);
            }
        }
    }
    /**
     * 审批详情(单表)
     *
     * @param paraMap
     * @return
     * @throws SQLException
     * @throws IOException
     */
    @SneakyThrows
    @GetMapping(value = "/loadMobilePageInfo")
    public ResponseResult<Object> loadMobilePageInfo(@RequestParam(required = false) Map<String, Object> paraMap) throws SQLException, IOException {
        paraMap = BaseUtil.decodeSecureMap(paraMap);
        String pageCode = this.service.getDao().getTableName();
        Map<String, Object> myDadaMap = new HashMap<>();
        //查询页面配置的sql语句
        StringBufferProxy sqlForAppPage = new StringBufferProxy();
        StringBufferProxy sqlForAppPageTab = new StringBufferProxy();
        sqlForAppPage.appendSingle("code='{0}' and enabled=1", pageCode);
        //获取页面信息
        AppPageEntity page = appPageService.queryObjectByWhere(sqlForAppPage.toString());
        //获取tab信息
        sqlForAppPageTab.appendSingle("pageid='{0}' and enabled=1", page.getId());
        List<Map<String, Object>> appPageTabList = appPageTabService.queryMapByWhere(sqlForAppPageTab.toString());
        //获取主Tab(list中只有一个mainTab)
        List<Map<String, Object>> listMain = appPageTabList.stream().filter(b -> "mainList".equals(ConvertUtil.convertToString(b.get("code")))).collect(Collectors.toList());
        //获取节点信息
        Map<String, Object> mainListData1 = this.service.queryMapById(paraMap.get("id").toString());//主表信息

        CboApprovalNodeInsEntity queryById = cboApprovalNodeInsService.queryObjectByWhere("flowid = '" + mainListData1.get("flowid").toString() + "'");
        Map<String, Object> mainTab = listMain.get(0);
        //如果此页面有一个tab则只需要处理主表数据
        if (appPageTabList.size() <= 1) {
            //取数据
            Map<String, Object> mainListData = this.service.queryMapById(paraMap.get("id").toString());
            //将取出的详细数据放入
            List<Map<String, Object>> mainList = new ArrayList<>();
            mainList.add(mainListData);
            // 其他主表数据
            mainListExtraData(paraMap, mainListData);
            //塞入数据（数据的key约定为“表名+‘List’”）
            myDadaMap.put("mainList", mainList);
            //获取页面（约定：app管理页面配置中的页面编码对应controller表名）
            appPageService.getPageInfo(this.service.getDao().getTableName(), myDadaMap);
            return ResponseResult.ok(myDadaMap);
        } else {
            //处理多tab逻辑（约定：1.mainList为单据信息 2.其他Tab信息：扩展1字段：查询此tab的controller 2.扩展2字段：主tab中的字段 3.扩展3字段：此tab中的字段）
            //主表数据
            Map<String, Object> mainListData = this.service.queryMapById(paraMap.get("id").toString());
            mainListExtraData(paraMap, mainListData);

            //将取出的详细数据放入
            List<Map<String, Object>> mainList = new ArrayList<>();
            mainList.add(mainListData);
            //塞入主表数据数据（数据的key约定为“表名+‘List’”）
            myDadaMap.put("mainList", mainList);
            //查询其他tab数据
            for (Map<String, Object> tabItem : appPageTabList) {
                if (!"mainList".equals(ConvertUtil.convertToString(tabItem.get("code")))) {
                    // 子表action
                    MpmController basicSubAction = (MpmController) SpringUtil.getBean(ConvertUtil.convertToString(tabItem.get("extendfield1")));
                    //查询子表数据的sql语句
                    StringBufferProxy sqlForSub = new StringBufferProxy();
                    //主tab字段名称
                    String mainTabFieldStr = ConvertUtil.convertToString(tabItem.get("extendfield2"));
                    //此tab字段名称
                    String subTabFieldStr = ConvertUtil.convertToString(tabItem.get("extendfield3"));
                    // app模板页面id
                    String tabTemplateId = ConvertUtil.convertToString(tabItem.get("extendfield4"));

                    //拼装此tab需要的sql
                    sqlForSub.appendSingle("{0} = '{1}'", subTabFieldStr, ConvertUtil.convertToString(mainListData.get(mainTabFieldStr)));
                    // 复盘-评分细则内容，修改sql
                    if("MpmProjectBidScoreReview".equals(ConvertUtil.convertToString(tabItem.get("relationdata")))) {
                        sqlForSub.appendSingle(" and times = '{0}' and type in ({1}) order by type asc, id asc ", MpmSystemConst.BidScoreTimes.thirdTime, MpmSystemConst.BidScoreType.firstType + "," + MpmSystemConst.BidScoreType.secondType);
                    }
                    if ("MpmProjectBidScoreOfferReview".equals(ConvertUtil.convertToString(tabItem.get("relationdata")))) {
                        sqlForSub.appendSingle(" and times = '{0}' and type = '{1}' and targetscore is not null order by type asc, id asc ", MpmSystemConst.BidScoreTimes.thirdTime, MpmSystemConst.BidScoreType.thirdType);
                    }
                    //查询子表数据
                    List<Map<String, Object>> subList = basicSubAction.service.queryMapByWhere(sqlForSub.toString());
                    if ("MpmProjectBidScoreReview".equals(ConvertUtil.convertToString(tabItem.get("relationdata")))) {
                        mpmProjectBidScoreService.convertClobToStringBidScore(subList);
                    }
                    if ("MpmProjectWinbidinfo".equals(ConvertUtil.convertToString(tabItem.get("relationdata")))) {
                        mpmProjectWinBidInfoService.changeBidMoney(subList);
                    }
                    //将取出的详细数据放入
                    myDadaMap.put(ConvertUtil.convertToString(tabItem.get("relationdata")), subList);
                }
            }
            // 当前节点不为空时添加附件信息
            if (queryById != null) {
                ICboAttachmentService cboAttachmentService = (CboAttachmentService) SpringUtil.getBean("cboAttachmentService");
                List<String> fieldList = new ArrayList<>();
                fieldList.add("filetype");
                fieldList.add("filesize");
                fieldList.add("displayname");
                fieldList.add("sourcetype");
                fieldList.add("id");
                List<Map<String, Object>> attachList = new ArrayList<>();
                // 如果是项目合同信息则只需要根据sourceid查询即可（合同流程中有多个附件）
                if (this.service.getDao().getTableName().equals("PmContract")) {
                    StringBufferProxy whereSqlForAttachList = new StringBufferProxy();
                    whereSqlForAttachList.appendSingle("sourceid = '{0}' and sourcetype in ('PmContract','PmSignContract') ", ConvertUtil.convertToString(paraMap.get("id")));
                    attachList = cboAttachmentService.queryMapFieldsByWhere(whereSqlForAttachList.toString(), fieldList);
                } else {
                    attachList = cboAttachmentService.queryMapFieldsByWhere("sourceid=" + ConvertUtil.convertToString(paraMap.get("id")) + " and sourcetype='" + queryById.getSourcetype() + "'", fieldList);

                }
                myDadaMap.put("attachmentList", attachList);
            }
            appPageService.getPageInfo(pageCode, myDadaMap);
            return ResponseResult.ok(myDadaMap);
        }
    }
}
